{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ancill\n",
      "emissions\n",
      "lat\n",
      "lon\n"
     ]
    }
   ],
   "source": [
    "import h5py\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "from osgeo import gdal,osr\n",
    "import matplotlib.pyplot as plt\n",
    "import os\n",
    "\n",
    "output_dir=\"D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4\\\\2020_tiff\"\n",
    "f=h5py.File(\"D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4\\GFED4.1s_2020_beta.hdf5\")\n",
    "resolution=0.25\n",
    "os.makedirs(output_dir,exist_ok=True)\n",
    "lat=f['lat']\n",
    "lon=f['lon']\n",
    "lat=np.array(lat)\n",
    "lon=np.array(lon)\n",
    "burned_area=f['burned_area']\n",
    "nrows,ncols=np.array(lat).shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4\\2015_tiff\\burned_fraction_01.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4\\2015_tiff\\burned_fraction_02.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4\\2015_tiff\\burned_fraction_03.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4\\2015_tiff\\burned_fraction_04.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4\\2015_tiff\\burned_fraction_05.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4\\2015_tiff\\burned_fraction_06.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4\\2015_tiff\\burned_fraction_07.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4\\2015_tiff\\burned_fraction_08.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4\\2015_tiff\\burned_fraction_09.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4\\2015_tiff\\burned_fraction_10.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4\\2015_tiff\\burned_fraction_11.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4\\2015_tiff\\burned_fraction_12.tif\n"
     ]
    }
   ],
   "source": [
    "burned_fraction=[]\n",
    "for month in burned_area:\n",
    "    burned_fraction=np.array(f[\"/burned_area/\"+month]['burned_fraction'])\n",
    "\n",
    "    #创建tif文件\n",
    "    tiff_file=os.path.join(output_dir,f\"burned_fraction_{month}.tif\")\n",
    "    driver=gdal.GetDriverByName(\"GTiff\")\n",
    "    dataset=driver.Create(tiff_file,ncols,nrows,1,gdal.GDT_Float32)\n",
    "    \n",
    "    #设置地理变换参数\n",
    "    lon_min=lon.min()-resolution/2\n",
    "    lat_max=lat.max()+resolution/2\n",
    "    print(lon_min,lat_max)\n",
    "    #geo_transform=（左上角x坐标，水平分辨率，旋转参数，左上角y坐标，旋转参数，-垂直分辨率）\n",
    "    geo_transform=(lon_min,resolution,0,lat_max,0,-resolution)\n",
    "    dataset.SetGeoTransform(geo_transform)\n",
    "\n",
    "    #设置投影\n",
    "    srs=osr.SpatialReference()\n",
    "    srs.ImportFromEPSG(4326)\n",
    "    dataset.SetProjection(srs.ExportToWkt())\n",
    "\n",
    "    #写入数据\n",
    "    band=dataset.GetRasterBand(1)\n",
    "    band.WriteArray(burned_fraction)\n",
    "    band.FlushCache()\n",
    "\n",
    "    dataset=None\n",
    "    print(f\"TIFF文件已保存到{tiff_file}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2020_beta"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ancill\n",
      "emissions\n",
      "lat\n",
      "lon\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4s\\2020New_tiff\\burned_fraction_01.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4s\\2020New_tiff\\burned_fraction_02.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4s\\2020New_tiff\\burned_fraction_03.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4s\\2020New_tiff\\burned_fraction_04.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4s\\2020New_tiff\\burned_fraction_05.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4s\\2020New_tiff\\burned_fraction_06.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4s\\2020New_tiff\\burned_fraction_07.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4s\\2020New_tiff\\burned_fraction_08.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4s\\2020New_tiff\\burned_fraction_09.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4s\\2020New_tiff\\burned_fraction_10.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4s\\2020New_tiff\\burned_fraction_11.tif\n",
      "-180.0 90.0\n",
      "TIFF文件已保存到D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4s\\2020New_tiff\\burned_fraction_12.tif\n"
     ]
    }
   ],
   "source": [
    "import h5py\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "from osgeo import gdal,osr\n",
    "import matplotlib.pyplot as plt\n",
    "import os\n",
    "\n",
    "output_dir=\"D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4s\\\\2020New_tiff\"\n",
    "f=h5py.File(\"D:\\Lenovo\\Desktop\\云南大学\\毕业设计\\毕设数据\\原始数据\\生物质燃烧面积\\GFED4s\\GFED4.1s_2020_beta.hdf5\")\n",
    "resolution=0.25\n",
    "os.makedirs(output_dir,exist_ok=True)\n",
    "for key in f.keys():\n",
    "    print(key)\n",
    "\n",
    "lat=f['lat']\n",
    "lon=f['lon']\n",
    "lat=np.array(lat)\n",
    "lon=np.array(lon)\n",
    "nrows,ncols=np.array(lat).shape\n",
    "#初始化月平均燃烧分数\n",
    "\n",
    "emissions=f['emissions']\n",
    "burned_fraction=[]\n",
    "for month in emissions:\n",
    "    month_fraction=np.zeros_like(lat,float)\n",
    "    daily_fraction=f[\"/emissions/\"+month][\"daily_fraction\"]\n",
    "    i=0\n",
    "    #读取每日燃烧分数并计算月平均值(概率并集法)\n",
    "    for day in daily_fraction:\n",
    "        oneday_fraction=np.array(daily_fraction[day])\n",
    "        not_burned_fraction=1-oneday_fraction\n",
    "        if i==0:       \n",
    "            monthly_total_not_burned=not_burned_fraction\n",
    "        else:\n",
    "            monthly_total_not_burned=monthly_total_not_burned*not_burned_fraction\n",
    "        i+=1\n",
    "        \n",
    "    month_fraction=1-monthly_total_not_burned    \n",
    "    #创建tif文件\n",
    "    tiff_file=os.path.join(output_dir,f\"burned_fraction_{month}.tif\")\n",
    "    driver=gdal.GetDriverByName(\"GTiff\")\n",
    "    dataset=driver.Create(tiff_file,ncols,nrows,1,gdal.GDT_Float32)\n",
    "    \n",
    "    #设置地理变换参数\n",
    "    lon_min=lon.min()-resolution/2\n",
    "    lat_max=lat.max()+resolution/2\n",
    "    print(lon_min,lat_max)\n",
    "    #geo_transform=（左上角x坐标，水平分辨率，旋转参数，左上角y坐标，旋转参数，-垂直分辨率）\n",
    "    geo_transform=(lon_min,resolution,0,lat_max,0,-resolution)\n",
    "    dataset.SetGeoTransform(geo_transform)\n",
    "\n",
    "    #设置投影\n",
    "    srs=osr.SpatialReference()\n",
    "    srs.ImportFromEPSG(4326)\n",
    "    dataset.SetProjection(srs.ExportToWkt())\n",
    "\n",
    "    #写入数据\n",
    "    band=dataset.GetRasterBand(1)\n",
    "    band.WriteArray(month_fraction)\n",
    "    band.FlushCache()\n",
    "\n",
    "    dataset=None\n",
    "    print(f\"TIFF文件已保存到{tiff_file}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "读取GFED5 burned_area数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "成功生成：D:\\Lenovo\\Desktop\\tmp\\CO2_tiff\\2020\\CO2_2020_01.tif\n",
      "成功生成：D:\\Lenovo\\Desktop\\tmp\\CO2_tiff\\2020\\CO2_2020_02.tif\n",
      "成功生成：D:\\Lenovo\\Desktop\\tmp\\CO2_tiff\\2020\\CO2_2020_03.tif\n",
      "成功生成：D:\\Lenovo\\Desktop\\tmp\\CO2_tiff\\2020\\CO2_2020_04.tif\n",
      "成功生成：D:\\Lenovo\\Desktop\\tmp\\CO2_tiff\\2020\\CO2_2020_05.tif\n",
      "成功生成：D:\\Lenovo\\Desktop\\tmp\\CO2_tiff\\2020\\CO2_2020_06.tif\n",
      "成功生成：D:\\Lenovo\\Desktop\\tmp\\CO2_tiff\\2020\\CO2_2020_07.tif\n",
      "成功生成：D:\\Lenovo\\Desktop\\tmp\\CO2_tiff\\2020\\CO2_2020_08.tif\n",
      "成功生成：D:\\Lenovo\\Desktop\\tmp\\CO2_tiff\\2020\\CO2_2020_09.tif\n",
      "成功生成：D:\\Lenovo\\Desktop\\tmp\\CO2_tiff\\2020\\CO2_2020_10.tif\n",
      "成功生成：D:\\Lenovo\\Desktop\\tmp\\CO2_tiff\\2020\\CO2_2020_11.tif\n",
      "成功生成：D:\\Lenovo\\Desktop\\tmp\\CO2_tiff\\2020\\CO2_2020_12.tif\n"
     ]
    }
   ],
   "source": [
    "import netCDF4 as nc\n",
    "import numpy as np\n",
    "from osgeo import gdal, osr\n",
    "import os\n",
    "\n",
    "# 输入输出路径配置\n",
    "input_nc = r\"D:\\Lenovo\\Desktop\\tmp\\monthly\\GFED5_Beta_monthly_2020.nc\"\n",
    "output_dir = r\"D:\\Lenovo\\Desktop\\tmp\\CO2_tiff\\2020\"\n",
    "os.makedirs(output_dir, exist_ok=True)\n",
    "\n",
    "# 打开NetCDF文件\n",
    "dataset = nc.Dataset(input_nc)\n",
    "burned_area = dataset['CO2'][:]  # 形状为(月份, 纬度, 经度)\n",
    "\n",
    "# 获取经纬度信息\n",
    "lat = dataset['lat'][:]    # 纬度数组\n",
    "lon = dataset['lon'][:]    # 经度数组\n",
    "n_time, n_lat, n_lon = burned_area.shape\n",
    "\n",
    "# 地理变换参数计算\n",
    "resolution = 0.25  # 单位：度\n",
    "lon_min = lon.min() - resolution/2\n",
    "lat_max = lat.max() + resolution/2\n",
    "\n",
    "# 创建WGS84投影\n",
    "srs = osr.SpatialReference()\n",
    "srs.ImportFromEPSG(4326)\n",
    "proj_wkt = srs.ExportToWkt()\n",
    "\n",
    "# 遍历每个月的数据\n",
    "for month in range(n_time):\n",
    "    # 输出文件名\n",
    "    tiff_path = os.path.join(output_dir, f\"CO2_{output_dir[-4:]}_{month+1:02d}.tif\")\n",
    "    \n",
    "    # 创建GeoTIFF文件\n",
    "    driver = gdal.GetDriverByName(\"GTiff\")\n",
    "    ds = driver.Create(\n",
    "        tiff_path,\n",
    "        xsize=n_lon,    # 经度方向像元数\n",
    "        ysize=n_lat,    # 纬度方向像元数\n",
    "        bands=1,\n",
    "        eType=gdal.GDT_Float32\n",
    "    )\n",
    "    \n",
    "    # 设置地理参考\n",
    "    ds.SetGeoTransform((\n",
    "        lon_min,  # 左上角经度\n",
    "        resolution,  # 经度分辨率\n",
    "        0,          # 旋转参数\n",
    "        lat_max,  # 左上角纬度\n",
    "        0,          # 旋转参数\n",
    "        -resolution  # 纬度分辨率（负号表示从北向南）\n",
    "    ))\n",
    "    \n",
    "    # 设置投影\n",
    "    ds.SetProjection(proj_wkt)\n",
    "    \n",
    "    # 写入数据（注意NetCDF数据可能需要进行维度翻转）\n",
    "    band = ds.GetRasterBand(1)\n",
    "    band.WriteArray(burned_area[month, :, :])  # 直接写入二维数组\n",
    "    \n",
    "    # 可选：设置无数据值（如果存在）\n",
    "    # band.SetNoDataValue(-9999)\n",
    "    \n",
    "    # 释放资源\n",
    "    band.FlushCache()\n",
    "    ds = None\n",
    "\n",
    "    print(f\"成功生成：{tiff_path}\")\n",
    "\n",
    "# 关闭NetCDF文件\n",
    "dataset.close()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "myenv2",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
